package com.kaba.security.handler;

import com.kaba.bean.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * @Author lvmengjie
 * @Date 2021/3/24
 * @Description 访问决策管理器
 */
@Component
public class CustomizeAccessDecisionManager implements AccessDecisionManager {


    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {


        //取出redis上的权限吗
        List<SysMenu> aaa= (List<SysMenu>) redisTemplate.opsForValue().get("kabam");
        System.out.println("我是redis中的权限吗"+aaa);
        //当前请求url对应的所有权限码  user:queryUsers
        Iterator<ConfigAttribute> iterator = collection.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute attribute = iterator.next();
            String code = attribute.getAttribute();//user:queryUsers
            System.out.println("我是code的请求路径"+code);
            //在UserDetailService中当初登陆成功从数据库查询的当前用户对应的角色下面所有的权限码
           // Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            //将前台传回的url和redis上的循环对比
            for (SysMenu sysMenu : aaa) {
                if (sysMenu.getPerms().equals(code)){
                    return;
                }
            }


//            for (GrantedAuthority authority : authorities) {
//
//            }

        }

        throw new AccessDeniedException("权限不足!");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
